<?php

namespace App\Http\Controllers\OpenShop\Feishu;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Controllers\BaseController;
use App\Http\Resources\OpenShop\InvestmentPromotion\OrderDetailResource;
use App\Http\Resources\OpenShop\ShopLocation\PlaceHolderSiteLocationResource;
use App\Library\Rms\RmsShopApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\OpenShop\Feishu\MissionTemplateService;
use App\Service\OpenShop\Feishu\OrganizationManageUserService;
use App\Service\OpenShop\Feishu\PermissionService;
use App\Service\OpenShop\Feishu\SelectionService;
use App\Service\OpenShop\Feishu\ShopCheckAcceptService;
use App\Service\OpenShop\Feishu\ShopEngineeringConstructionService;
use App\Service\OpenShop\Feishu\SiteMissionService;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use App\Service\OpenShop\Feishu\StartBusinessService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\SiteLocation\PlaceHolderSiteLocationService;
use App\Service\Rms\ShopService;
use Illuminate\Http\Request;
use Kuafu\File\FileUtil;

class SiteMissionController extends BaseController
{
    // 获取任务-开发经理状态的
    public function info(Request $request, int $id)
    {
        // isAll && 原生sql
        $dataPermission  = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);
        $orderPermission = (new PermissionService)->getOrderPermissionDataOrder($dataPermission, getRmsUserId());

        $info = SiteMissionService::info($id, $orderPermission, getRmsUserId());
        if (empty($info)) {
            throw new ResponseHttpException(BaseErrorCode::$MISSION_INFO_GET_FAIL);
        }

        $main = OpenShopMainProcessModel::query()->where('orderNo', $info['orderNo'])->first();
        if (!$main) {
            throw new ResponseHttpException(BaseErrorCode::$MISSION_INFO_GET_FAIL);
        }

        // 补充 info 字段数据
        $shopCode = OpenShopSignOrderModel::query()
                                          ->where('orderNo', $info['orderNo'])
                                          ->value('shopCode');

        if (empty($shopCode)) {
            throw new ResponseHttpException(BaseErrorCode::$MISSION_INFO_GET_FAIL);
        }

        $info['shopName'] = (new RmsShopApi)->getShopByCode($shopCode)['data']['name'] ?? '';
        $info['shopCode'] = $shopCode; // 门店编号

        // TODO 根据任务状态显示对应的数据
        $openShopLocationModel          = new OpenShopLocationModel;
        $investmentManagerInfo          = $openShopLocationModel->getInvestmentManager($info['orderNo']);
        $investmentLocation             = SelectionService::getInvestmentLocation($info['orderNo']);
        $investmentLocation['shopName'] = $info['shopName'];
        $investmentLocation['shopCode'] = $info['shopCode'];
        // 订单信息
        $orderSignInfo                               = OpenShopSignOrderModel::orderDetail($info['orderNo'], true);
        $orderDetail['baseInfo']                     = $orderSignInfo->getIterator()->current()->baseInfoRel;
        $spaceDesignInfo                             = SpaceDesignService::getMainInfo($info['orderNo']);
        $spaceDesignFileList                         = SpaceDesignService::handleSoftData($info['orderNo']);
        $shopEngineeringConstruction                 = ShopEngineeringConstructionService::detail($info['orderNo'])["detail"];
        $shopCheckAccept                             = ShopCheckAcceptService::detail($info['orderNo'])["detail"];
        $investmentLocation['shopLocationReportUrl'] = privateFilePath($investmentLocation['shopLocationReportUrl'] ?? '');
        $construction                                = SiteMissionService::buildInfo($info['orderNo']);

        if (!empty($shopCheckAccept)) {
            $construction['buildInfo']['manageId']    = $shopCheckAccept->manageId;
            $construction['buildInfo']['managerName'] = $shopCheckAccept->managerName;
        }

        // 门店选址信息
        $shopAddress = OpenShopAddressModel::getData($info['orderNo']) ?? [];

        $info['shopAddressPrefix'] = $shopAddress['addressPrefix'] ?? '';

        // 在筹备工作台,处理建店信息时,选择督导输入框自动填入该区域对应的督导,若该区域有多个督导,则空着
        if ($info['stepStatus'] == MissionTemplateEnum::STEP_STATUS_6) {
            $provinceCode = $shopAddress['provinceCode'] ?? '';
            $cityCode     = $shopAddress['cityCode'] ?? '';
            $areaCode     = $shopAddress['areaCode'] ?? '';

            $supervisorData = OrganizationManageUserService::getManagerByAddressCodes(
                OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER, $provinceCode, $cityCode, $areaCode
            );

            $construction['buildInfo']['managerId']    = $supervisorData['userId'] ?? 0;
            $construction['buildInfo']['managerName'] = $supervisorData['name'] ?? '';
        }

        $placeholder = new PlaceHolderSiteLocationService($info["orderNo"]);

        return $this->success([
            'missionInfo'                 => $info,
            'orderDetail'                 => $orderDetail,
            'investmentManagerInfo'       => $investmentManagerInfo, // 开发经理
            'investmentLocation'          => $investmentLocation, // 选址报告
            'spaceDesignInfo'             => $spaceDesignInfo, // 空间设计 基础信息
            'spaceDesignFileList'         => $spaceDesignFileList, // 空间设计图纸
            'shopEngineeringConstruction' => $shopEngineeringConstruction,
            'shopCheckAccept'             => $shopCheckAccept,
            'construction'                => $construction,
            'startBusiness'               => StartBusinessService::detail($info["orderNo"])["detail"],
            'placeholder'                 => empty($placeholder->getPlaceholderInfo()) ? null :
                PlaceHolderSiteLocationResource::collection([$placeholder->getPlaceholderInfo()])
                                               ->getIterator()->current(),
        ]);

    }

    public function index(Request $request)
    {
        $status        = $request->get('status', 0);
        $expiredStatus = $request->get('expiredStatus', 0);
        $missionName   = $request->get('missionName', '');
        $shopIds       = $request->get('shopIds', '');
        $pageNum       = (int)$request->get('pageNum', 1);
        $pageSize      = (int)$request->get('pageSize', 20);
        $handleUserId  = (int)$request->get('handleUserId', '');
//        $scope         = PermissionService::hasAll();
        $userId = getRmsUserId();

        // isAll && 原生sql
        $dataPermission  = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);
        $orderPermission = (new PermissionService)->getOrderPermissionDataOrder($dataPermission, $userId);

        return $this->success(SiteMissionService::paginateList($status, $expiredStatus, $pageNum, $pageSize,
            $orderPermission, $userId, $missionName, $shopIds, $handleUserId));
    }

}
